/**
* Author:LSP
* Date:2020-12-18
*/
// @导入引用开发环境
if (typeof require === 'undefined') require = importModule
const { Base } = require("./lsp环境")

// @小组件配置
const widgetConfigs = {
    // 是否是iPhone12mini
    isIphone12Mini: false,
    refreshInterval: 10, // 刷新时间--估算(单位：分钟)
    // 预览模式：0：小尺寸，1：中等尺寸，2：大尺寸，负数：不预览
    previewMode: 2,

    // 上背景图url
    bgUrl: "https://www.logosc.cn/uploads/resources/2018/11/28/1543395643.jpg",
    // 星期标题
    weekTitle: ['🙄 周日', '😪 周一', '🥱 周二', '🤨 周三', '🤓 周四', '🤩 周五', '🥳 周六'],
    // 日期字体大小
    dayFont: Font.lightMonospacedSystemFont(12),
    // 日期文字颜色
    dayColor: new Color('000000', 0.7),
    // 今天日期文字颜色
    currDayColor: new Color('FF0000', 0.7),
    // 非本月日期文字颜色
    nonDayColor: new Color('BBBBBB', 1),
    // 左侧日期字体
    calendarFont: Font.lightMonospacedSystemFont(20),
    // 左侧日期颜色
    calendarColor: new Color('000000', 0.6),
    // 左侧星期几字体
    weekTitleFont: Font.lightSystemFont(14),
    // 左侧星期几颜色
    weekTitleColor: new Color('FF0000', 1),
    // 农历字体
    lunarFont: Font.regularSystemFont(14),
    // 农历颜色
    lunarColor: new Color('000000', 1),
    // 遮罩颜色
    maskColor: new Color('FFFFFF', 0.7),

    padding: {
        top: 0, // 上边距
        left: 0, // 左边距
        bottom: 0, // 底边距
        right: 0, // 右边距
    },
}

// @定义小组件
class Widget extends Base {
    constructor(scriptName) {
        super(scriptName)
        // 初始化其他变量
        this.setSelectPicBg(false)
        this.paddingSetting(Object.assign(widgetConfigs.padding))
        this.refreshIntervalTime(widgetConfigs.refreshInterval)
        this.setPreViewSizeMode(widgetConfigs.previewMode)
    }

    //-------------------------------------

    /**
     * 获取顶部图片
     * @link 支持的所有tag：https://tuchong.com/explore/
     */
    async getTopBgPic() {
        let imgUrl = widgetConfigs.bgUrl
        const inputStr = this.getWidgetInput()
        if (inputStr.length > 0) {
            const url = `https://tuchong.com/rest/tags/${encodeURIComponent(inputStr)}/posts?page=1&count=20&order=weekly`
            const defaultHeaders = {
                "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36"
            }
            const response = await this.httpGet(url, true, defaultHeaders, null, true)
            if (response != undefined && response != null) {
                console.log(`图虫请求成功~~`)
                const postList = response.postList
                // 索引
                const item = this.getRandowArrValue(postList)
                if (item != undefined && item != null) {
                    // 图片  
                    const imgItem = this.getRandowArrValue(item.images)
                    if (imgItem != undefined && imgItem != null) {
                        imgUrl = `https://photo.tuchong.com/${imgItem.user_id}/f/${imgItem.img_id}.webp`
                    }
                }
            }
        }

        console.log(`顶部图片链接：${imgUrl}`)
        const img = await this.getImageByUrl(imgUrl, 'calendar-big')

        return img
    }

    /**
    * 获取月份有多少天
    * @param {number} year 
    * @param {number} month 
    */
    getDays(year, month) {
        var date = new Date(year, month, 0)
        return date.getDate()
    }

    /**
    * 获取当前月份的1号是星期几(0~6)
    */
    getCurrentFirstDayWeek() {
        const date = new Date()
        date.setDate(1)
        return date.getDay()
    }

    /**
    * 获取今天是星期几
    */
    getCurrDayWeekTitle() {
        var date = new Date()
        return widgetConfigs.weekTitle[date.getDay()]
    }

    /**
    * 在线获取农历信息
    */
    async getLunar(year, month, currDay) {
        const url = "https://www.iamwawa.cn/home/nongli/ajax"
        const defaultHeaders = {
            "Accept": "*/*",
            "Content-Type": "application/json"
        }
        const parameterList = [
            { "type": "solar" },
            { "year": `${year}` },
            { "month": `${month}` },
            { "day": `${currDay}` }
        ]

        const data = await this.httpPost(url, parameterList, true, defaultHeaders, null, true)
        return data
    }

    //-------------------------------------

    /**
     * @渲染小组件
     */
    async render() {
        // 日期
        const thisDate = new Date()
        // 年份
        const year = thisDate.getFullYear()
        // 月份
        const month = thisDate.getMonth() + 1
        // 日期
        const currDay = thisDate.getDate()

        // 上一个月的年份
        let preMonthYear = null
        // 上个月份
        let preMonth = null
        if (month == 1) {
            preMonthYear = year - 1
            preMonth = 12
        } else {
            preMonthYear = year
            preMonth = month - 1
        }
        // 上个月有多少天
        const preMonthDays = this.getDays(preMonthYear, preMonth)
        // 当前月份有多少天
        const currMonthDays = this.getDays(year, month)
        // 当前月份1号是星期几
        const currMonthFirstDay = this.getCurrentFirstDayWeek()
        // 开始日期数字
        const startNum = preMonthDays - currMonthFirstDay + 1
        // 日期数据分割
        const dayRowArr = []
        const dayRowArr1 = []
        const dayRowArr2 = []
        const dayRowArr3 = []
        const dayRowArr4 = []
        const dayRowArr5 = []
        const dayRowArr6 = []
        dayRowArr.push(dayRowArr1)
        dayRowArr.push(dayRowArr2)
        dayRowArr.push(dayRowArr3)
        dayRowArr.push(dayRowArr4)
        dayRowArr.push(dayRowArr5)
        dayRowArr.push(dayRowArr6)

        // 第一行日期填充
        for (let index = 0; index < currMonthFirstDay; index++) {
            // 上个月
            dayRowArr1.push(
                {
                    num: startNum + index,
                    font: widgetConfigs.dayFont,
                    color: widgetConfigs.nonDayColor
                }
            )
        }
        let lastDayIndex = 0
        for (let index = 0; index < 7 - currMonthFirstDay; index++) {
            // 当前月
            lastDayIndex = index + 1
            let fontColor = widgetConfigs.dayColor
            if (lastDayIndex == currDay) {
                fontColor = widgetConfigs.currDayColor
            }
            dayRowArr1.push(
                {
                    num: lastDayIndex,
                    font: widgetConfigs.dayFont,
                    color: fontColor
                }
            )
        }

        // 第二行日期填充
        for (let index = 0; index < 7; index++) {
            lastDayIndex = lastDayIndex + 1
            let fontColor = widgetConfigs.dayColor
            if (lastDayIndex == currDay) {
                fontColor = widgetConfigs.currDayColor
            }
            dayRowArr2.push(
                {
                    num: lastDayIndex,
                    font: widgetConfigs.dayFont,
                    color: fontColor
                }
            )
        }

        // 第三行
        for (let index = 0; index < 7; index++) {
            lastDayIndex = lastDayIndex + 1
            let fontColor = widgetConfigs.dayColor
            if (lastDayIndex == currDay) {
                fontColor = widgetConfigs.currDayColor
            }
            dayRowArr3.push(
                {
                    num: lastDayIndex,
                    font: widgetConfigs.dayFont,
                    color: fontColor
                }
            )
        }

        // 第四行
        for (let index = 0; index < 7; index++) {
            lastDayIndex = lastDayIndex + 1
            let fontColor = widgetConfigs.dayColor
            if (lastDayIndex == currDay) {
                fontColor = widgetConfigs.currDayColor
            }
            dayRowArr4.push(
                {
                    num: lastDayIndex,
                    font: widgetConfigs.dayFont,
                    color: fontColor
                }
            )
        }

        // 第五行
        let nextMonthDayIndex = 0
        if (lastDayIndex < currMonthDays) {
            let remainDays = currMonthDays - lastDayIndex
            remainDays = Math.min(7, remainDays)
            for (let index = 0; index < remainDays; index++) {
                lastDayIndex = lastDayIndex + 1
                let fontColor = widgetConfigs.dayColor
                if (lastDayIndex == currDay) {
                    fontColor = widgetConfigs.currDayColor
                }
                dayRowArr5.push(
                    {
                        num: lastDayIndex,
                        font: widgetConfigs.dayFont,
                        color: fontColor
                    }
                )
            }

            // 用下个月的日期填充
            if (remainDays < 7) {
                for (let index = 0; index < 7 - remainDays; index++) {
                    nextMonthDayIndex = index + 1
                    dayRowArr5.push(
                        {
                            num: nextMonthDayIndex,
                            font: widgetConfigs.dayFont,
                            color: widgetConfigs.nonDayColor
                        }
                    )
                }
            }
        }

        // 第六行
        if (lastDayIndex < currMonthDays) {
            let remainDays = currMonthDays - lastDayIndex
            remainDays = Math.min(7, remainDays)
            for (let index = 0; index < remainDays; index++) {
                lastDayIndex = lastDayIndex + 1
                let fontColor = widgetConfigs.dayColor
                if (lastDayIndex == currDay) {
                    fontColor = widgetConfigs.currDayColor
                }
                dayRowArr6.push(
                    {
                        num: lastDayIndex,
                        font: widgetConfigs.dayFont,
                        color: fontColor
                    }
                )
            }

            // 用下个月的日期填充
            if (remainDays < 7) {
                for (let index = 0; index < 7 - remainDays; index++) {
                    nextMonthDayIndex = nextMonthDayIndex + 1
                    dayRowArr6.push(
                        {
                            num: nextMonthDayIndex,
                            font: widgetConfigs.dayFont,
                            color: widgetConfigs.nonDayColor
                        }
                    )
                }
            }
        } else {
            // 用下个月的日期填充
            for (let index = 0; index < 7; index++) {
                nextMonthDayIndex = nextMonthDayIndex + 1
                dayRowArr6.push(
                    {
                        num: nextMonthDayIndex,
                        font: widgetConfigs.dayFont,
                        color: widgetConfigs.nonDayColor
                    }
                )
            }
        }


        //-------------------------------------
        const widget = new ListWidget()
        const contentStack = widget.addStack()
        contentStack.layoutVertically()
        //
        const topBgViewStack = contentStack.addStack()
        const width = this.getWidgetWidthSize('大号', widgetConfigs.isIphone12Mini)
        topBgViewStack.size = new Size(width, 200)

        //
        contentStack.addSpacer()
        const calendarStack = contentStack.addStack()
        calendarStack.size = new Size(width, 0)
        calendarStack.layoutHorizontally()
        calendarStack.addSpacer(10)
        calendarStack.addSpacer()

        // 左侧stack
        let leftStack = calendarStack.addStack()
        leftStack.layoutVertically()
        leftStack.addSpacer()
        // 日期
        let monthText = leftStack.addText(this.getDateStr(thisDate, "MM月d日"))
        monthText.font = widgetConfigs.calendarFont
        monthText.textColor = widgetConfigs.calendarColor
        monthText.shadowColor = widgetConfigs.calendarColor
        monthText.shadowOffset = new Point(1, 1)
        monthText.shadowRadius = 1
        // 星期几
        leftStack.addSpacer(8)
        let currWeekDayText = leftStack.addText(this.getCurrDayWeekTitle() + " ☞☞")
        currWeekDayText.font = widgetConfigs.weekTitleFont
        currWeekDayText.textColor = widgetConfigs.weekTitleColor
        // 农历信息
        leftStack.addSpacer(8)
        let lunarInfo = await this.getLunar(year, month, currDay)
        let infoLunarText = lunarInfo.data.lunar
        infoLunarText = infoLunarText.substring(12, infoLunarText.length)
        let lunarText = leftStack.addText(infoLunarText)
        lunarText.font = widgetConfigs.lunarFont
        lunarText.textColor = widgetConfigs.lunarColor
        lunarText.leftAlignText()
        //
        leftStack.addSpacer()
        ///////////////////////////


        // 右侧stack
        calendarStack.addSpacer()
        const rightStack = calendarStack.addStack()
        rightStack.layoutVertically()
        calendarStack.backgroundColor = widgetConfigs.maskColor
        rightStack.addSpacer()

        // 日期绘制
        dayRowArr.forEach(row => {
            let rowStack = rightStack.addStack()
            rowStack.layoutHorizontally()
            rightStack.addSpacer(6)
            row.forEach(item => {
                let itemStack = rowStack.addStack()
                itemStack.layoutHorizontally()
                itemStack.size = new Size(30, 0)
                let rowText = itemStack.addText(`${item.num}`)
                rowText.font = item.font
                rowText.textColor = item.color
                rowText.shadowColor = item.color
                rowText.shadowOffset = new Point(1, 1)
                rowText.shadowRadius = 1
                rowText.centerAlignText()
            })
        })
        calendarStack.addSpacer()
        const bottomStack = widget.addStack()
        bottomStack.size = new Size(width, 10)
        bottomStack.backgroundColor = widgetConfigs.maskColor

        const bgImg = await this.getTopBgPic()
        widget.backgroundImage = bgImg
        //-------------------------------------
        return widget
        //-------------------------------------
    }
}

// @运行测试
const { Running } = require("./lsp环境")
await Running(Widget, Script.name())